#!/bin/sh

# 找到运行的tomcat，干掉，删除webapp下所有内容，放入新的war包，启动
# 找不到会失败

set -x

# Return pid for port
# @param param1 required port
function pid_for_port {
	restartPid=`lsof -i:$1 | sed -n "2p" | awk '{print $2}'`
	echo ${restartPid}
}

function tomcat_path_for_pid {
	tomcat_path=`ps -ef | grep $1 | tr -s ' ' '\\n' | grep 'Dcatalina.home' | tr -s '=' '\\n' | sed -n "2p"`
	echo ${tomcat_path}
}

if [ $# != 3]; then
	echo "deployTomcat tomcatPort warFilePath deployPath"
	exit -1
fi

tomcat_port=$1
war_file_path=$2
deploy_path=$3


if [ ! -f "${war_file_path}" ]; then
	echo "war file not exists, ${war_file_path}"
	exit -1
fi

tomcat_pid=`pid_for_port ${tomcat_port}`
tomcat_path=`tomcat_path_for_pid ${tomcat_pid}`

if [ ! -d "${tomcat_path}" ]; then
	echo "standby tomcat path not exists, ${tomcat_path}"
	exit -1
fi

kill -9 ${tomcat_pid}

rm -rf ${tomcat_path}/bin/catalina.pid
rm -rf ${tomcat_path}/logs/*
rm -rf ${tomcat_path}/webapps/*

cp ${war_file_path} ${tomcat_path}/webapps/${deploy_path}.war

nohup ${tomcat_path}/bin/startup.sh & 